# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/8/12
library(optparse)
library(magrittr)
library(tidyverse)

option_list <- list(
  make_option("--i", default = "AllMet1.csv", type = "character", help = "raw metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--config", default = "config.csv", type = "character", help = "config file"),
  make_option("--d", type = 'character', action = "store", default = "./", help = "the database direcotry")
)
opt <- parse_args(OptionParser(option_list = option_list))


args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/metabo_base.R"))

mSet <- InitDataObjects("conc", "pathora", FALSE)

configData <- read.csv(opt$config, header = F, stringsAsFactors = F) %>%
  set_colnames(c("arg", "value")) %>%
  column_to_rownames("arg")

isNormal <- configData["isNormal", "value"] == "T"
isLoess <- configData["isLoess", "value"] == "T"

rawData <- read_csv("02_AllMet_Raw_Missing_Value_Filled.csv")

if (isLoess) {
  rawData <- read_csv("03_AllMet_Raw_NormQCsamples.csv")
}

if (isNormal) {
  rawData <- read_csv("03_AllMet_Raw_NormArea.csv")
}

keggInfoData <- read_tsv("keggInfo.txt") %>%
  select(c("Class", "HMDB", "KEGG", "Raw_Metabolite", "Metabolite")) %>%
  rename(HMDB = HMDB, KEGG = KEGG)

nrow(keggInfoData)

rawDataColumn <- rawData %>%
  select(-c("Raw_Metabolite"))

lowerKeggData <- keggInfoData %>%
  mutate(lowerName = tolower(Raw_Metabolite)) %>%
  select(-"Raw_Metabolite")

finalColumnNames <- c("Class", "HMDB", "KEGG", "Raw_Metabolite", "Metabolite")
finalColumnNames <- c(finalColumnNames, colnames(rawDataColumn))

nrow(rawData)
nrow(lowerKeggData)

outData <- rawData %>%
  mutate(Metabolite = iconv(enc2utf8(Raw_Metabolite), sub = "byte")) %>%
  mutate(lowerName = tolower(Metabolite)) %>%
  select(-c("Metabolite")) %>%
  left_join(lowerKeggData, by = c("lowerName")) %>%
  select(-c("lowerName")) %>%
  select(finalColumnNames) %>%
  mutate_at(vars("Class"), function(x) {
    replace_na(x, "Unknown")
  }) %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    id <- result[1, "Metabolite"]
    if (is.na(id)) {
      result %>% mutate(Metabolite = Raw_Metabolite)
    }else result
  }) %>%
  ungroup() %>%
  select(-Raw_Metabolite)

keggs <- outData %>%
  .$KEGG
keggs

cmpd.vec <- keggs
mSet <- Setup.MapData(mSet, cmpd.vec)
mSet <- CrossReferencing(mSet, "kegg", dataDir = opt$d)
mSet <- CreateMappingResultTable(mSet, dataDir = opt$d)

species <- configData["species", "value"]
isSmp <- configData["isSmp", "value"]
library <- if (isSmp == "kegg") {
  species
}else str_c(species, "-smpdb", sep = "")
libs <- unlist(strsplit(library, "-"))
if (length(libs) > 1) {
  mSet <- SetSMPDB.PathLib(mSet, libs[1], dataDir = opt$d)
  mSet <- SetOrganism(mSet, libs[1])
}else {
  mSet <- SetKEGG.PathLib(mSet, library, dataDir = opt$d)
}
mSet <- SetMetabolomeFilter(mSet, F)
hasSmp <- if (isSmp == "kegg") {
  FALSE
}else TRUE
mSet <- MyCalculateOraScore(mSet, dataDir = opt$d, hasSmp)

fileName <- "pathway.txt"
outData <- if (!file.exists(fileName)) {
  outData %>%
    mutate(Pathway = NA) %>%
    select(c("Class", "HMDB", "KEGG", "Metabolite", "Pathway"), everything())
}else {
  pathwayData <- read_tsv(fileName)
  outData %>%
    left_join(pathwayData, by = c("KEGG")) %>%
    select(c("Class", "HMDB", "KEGG", "Metabolite", "Pathway"), everything())
}

outData

write_csv(outData, "04_AllMet_Pathway.csv")




